/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GUITorrent.java
 *
 * Created on Mar 18, 2011, 12:38:46 PM
 */

package view;


import java.awt.Component;
import model.*;
import helper.*;
import java.awt.Color;
import java.awt.Dimension;
import java.io.*;
import javax.swing.JPopupMenu;
import javax.swing.JFileChooser;
import java.util.*;
import java.util.logging.*;
import java.io.StringReader;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.border.Border;
import main.Peer;
import main.PeerDownloader;
import main.PeerHandler;
import main.Tracker;



/**
 *
 * @author kuroshaki
 */
public class GUITorrent extends javax.swing.JFrame {
    private Component frame;
    private JList list;

    /** Creates new form GUITorrent */
    public GUITorrent() {
        initComponents();
        BasicThread listener = new BasicThread();

        listener.start();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        popup = new java.awt.PopupMenu();
        menupopup = new java.awt.Menu();
        bodypanel = new javax.swing.JPanel();
        infopanel = new javax.swing.JPanel();
        scrollinfo = new javax.swing.JScrollPane();
        torrentlist = new javax.swing.JList();
        infotab = new javax.swing.JTabbedPane();
        general = new javax.swing.JScrollPane();
        generalinfo = new javax.swing.JTextField();
        peers = new javax.swing.JScrollPane();
        peersinfo = new javax.swing.JTextField();
        Files = new javax.swing.JScrollPane();
        files = new javax.swing.JTextField();
        addtorrent = new javax.swing.JButton();
        createtorrent = new javax.swing.JButton();
        delete = new javax.swing.JButton();
        play = new javax.swing.JButton();
        stop = new javax.swing.JButton();
        up = new javax.swing.JButton();
        down = new javax.swing.JButton();
        about = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        filemenu = new javax.swing.JMenu();
        additem = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JPopupMenu.Separator();
        createitem = new javax.swing.JMenuItem();
        jSeparator3 = new javax.swing.JPopupMenu.Separator();
        exititem = new javax.swing.JMenuItem();
        helpmenu = new javax.swing.JMenu();
        aboutitem = new javax.swing.JMenuItem();

        popup.setLabel("popupMenu1");
        popup.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                popupActionPerformed(evt);
            }
        });

        menupopup.setLabel("menu1");
        menupopup.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menupopupActionPerformed(evt);
            }
        });
        popup.add(menupopup);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        infopanel.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));

        torrentlist.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                torrentlistMouseClicked(evt);
            }
        });
        scrollinfo.setViewportView(torrentlist);

        javax.swing.GroupLayout infopanelLayout = new javax.swing.GroupLayout(infopanel);
        infopanel.setLayout(infopanelLayout);
        infopanelLayout.setHorizontalGroup(
            infopanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 767, Short.MAX_VALUE)
            .addGroup(infopanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(infopanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(scrollinfo, javax.swing.GroupLayout.PREFERRED_SIZE, 747, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        infopanelLayout.setVerticalGroup(
            infopanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 177, Short.MAX_VALUE)
            .addGroup(infopanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(infopanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(scrollinfo, javax.swing.GroupLayout.DEFAULT_SIZE, 155, Short.MAX_VALUE)
                    .addContainerGap()))
        );

        infotab.setName("General"); // NOI18N
        infotab.setPreferredSize(new java.awt.Dimension(30, 50));

        generalinfo.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                generalinfoMouseClicked(evt);
            }
        });
        general.setViewportView(generalinfo);

        infotab.addTab("general", general);

        peers.setViewportView(peersinfo);

        infotab.addTab("peers", peers);

        Files.setViewportView(files);

        infotab.addTab("files", Files);

        javax.swing.GroupLayout bodypanelLayout = new javax.swing.GroupLayout(bodypanel);
        bodypanel.setLayout(bodypanelLayout);
        bodypanelLayout.setHorizontalGroup(
            bodypanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(bodypanelLayout.createSequentialGroup()
                .addGroup(bodypanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(bodypanelLayout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(infopanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(bodypanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(infotab, javax.swing.GroupLayout.PREFERRED_SIZE, 758, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        bodypanelLayout.setVerticalGroup(
            bodypanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, bodypanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(infopanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(infotab, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        infotab.getAccessibleContext().setAccessibleName("General");

        addtorrent.setText("add Torrent");
        addtorrent.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addtorrentActionPerformed(evt);
            }
        });

        createtorrent.setText("create Torrent");
        createtorrent.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createtorrentActionPerformed(evt);
            }
        });

        delete.setText("del");
        delete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteActionPerformed(evt);
            }
        });

        play.setText("play");
        play.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                playActionPerformed(evt);
            }
        });

        stop.setText("stop");
        stop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stopActionPerformed(evt);
            }
        });

        up.setText("up");

        down.setText("down");

        about.setText("about");
        about.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aboutActionPerformed(evt);
            }
        });

        filemenu.setText("File");

        additem.setText("Add Torrent");
        additem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addtorrentActionPerformed(evt);
            }
        });
        filemenu.add(additem);
        filemenu.add(jSeparator2);

        createitem.setText("Create Torrent");
        createitem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createtorrentActionPerformed(evt);
            }
        });
        filemenu.add(createitem);
        filemenu.add(jSeparator3);

        exititem.setText("Exit");
        exititem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exititemActionPerformed(evt);
            }
        });
        filemenu.add(exititem);

        jMenuBar1.add(filemenu);

        helpmenu.setText("Help");
        helpmenu.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                helpmenuStateChanged(evt);
            }
        });
        helpmenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aboutActionPerformed(evt);
            }
        });

        aboutitem.setText("About ThisTorrent");
        aboutitem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aboutActionPerformed(evt);
            }
        });
        helpmenu.add(aboutitem);

        jMenuBar1.add(helpmenu);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(addtorrent)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(createtorrent)
                        .addGap(81, 81, 81)
                        .addComponent(delete)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(play)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(stop)
                        .addGap(52, 52, 52)
                        .addComponent(up)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(down)
                        .addGap(63, 63, 63)
                        .addComponent(about))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(bodypanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(addtorrent)
                    .addComponent(createtorrent)
                    .addComponent(about)
                    .addComponent(down)
                    .addComponent(up)
                    .addComponent(play)
                    .addComponent(stop)
                    .addComponent(delete))
                .addGap(18, 18, 18)
                .addComponent(bodypanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        getAccessibleContext().setAccessibleName("this Torrent");

        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    private void addtorrentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addtorrentActionPerformed
        // TODO add your handling code here:

        final JFileChooser fileChooser=new JFileChooser();

        int returnVal = fileChooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            try {
              // What to do with the file, e.g. display it in a TextArea

                String st = file.getAbsolutePath();
                String nama = file.getName();

                char [] filePath = new char[st.length() - 8];
                for (int i = 0; i < filePath.length; ++i){
                    filePath[i] = st.charAt(i);
                }

                String filename = new String(filePath);

                boolean cek = true;
                for(int y=0;y<arrayTampung.size();y++){
                    if(strings.get(y).equalsIgnoreCase(st)){
                        cek = false;
                        break;
                    }
                }

                if(cek){
                    strings.add(st);

                    tor = new Torrent(st);
                    torrentGUI.add(tor);
                    String info = new String();
                    info="Nama File : "+tor.getFileName()+"\n";
                    info=info+"File Length : "+tor.getFileLength()+"\n";
                    info=info+"Length : "+tor.getLength()+"\n";
                    //info=info+"Announcement"+"\n";

                    if(!new File(filename).exists()){
                        createFile(tor.getFileLength(), filename);
                        System.out.println("belum ada gan\n");
                    }else{
                        System.out.println("sudah ada gan\n");
                    }

                    
                    StringReader myst = new StringReader(info);
                    generalinfo.read(myst, null );

                    per = new Peer(Utilities.TRACKER_HOST);
                    boolean bool = false;
                    Tampung t = new Tampung(per, bool);
                    arrayTampung.add(t);


                    String infopeer = new String();
                    infopeer = "Daftar Peer yang memiliki file : "+tor.getFileName()+" \n\n";
                    infopeer = infopeer+"Jumlah Peer yang memiliki file complete : "+0+"\n";
                    infopeer = infopeer+"Jumlah Peer yang memiliki file incomplete : "+0+"\n";
                    //infopeer = infopeer+"Daftar peer : \n";
                    /*for(int y=0;y<resp.getPeers().size();y++){
                        infopeer = infopeer+resp.getPeers().get(y).getAddress().toString();
                    }*/

                    StringReader myst1 = new StringReader(infopeer);
                    peersinfo.read(myst1, null);

                    String fil = new String();
                    System.out.println(st + " " + tor.getFileName());
                    boolean[] status = tor.compareDownloadedFile(tor.getResultPath());
                    for(int y=0;y<status.length;y++){
                        fil+="Part ke "+y;
                        if(status[y]){
                            fil+="\tcompleted\n";
                        }else{
                            fil+="\tnot completed\n";
                        }
                    }

                    myst1 = new StringReader(fil);
                    files.read(myst1, null);


                    final String[] daftar = new String[strings.size()];
                    strings.toArray(daftar);

                    torrentlist.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
                    torrentlist.setLayoutOrientation(JList.VERTICAL_WRAP);
                    torrentlist.setVisibleRowCount(-1);
                    torrentlist.setModel(new javax.swing.AbstractListModel() {
                        String[] strings = daftar;
                        public int getSize() { return strings.length; }
                        public Object getElementAt(int i) { return strings[i]; }
                    });

                    // buat file hasil jika belum ada
                    /*if(){
                        File f;
                        f=new File("myfile.txt");
                        if(!f.exists()){
                            f.createNewFile();
                            
                        }
                    }*/
                        
                }else{
                    JOptionPane.showMessageDialog(frame, "File telah yang dipilih sudah ada");
                }
                
            } catch (IOException ex) {
              System.out.println("problem accessing file"+file.getAbsolutePath());
            }
        } else {
            System.out.println("File access cancelled by user.");
        }
        
    }//GEN-LAST:event_addtorrentActionPerformed

    private void exititemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exititemActionPerformed
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_exititemActionPerformed

    private void createtorrentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createtorrentActionPerformed
        // TODO add your handling code here:

        final JFileChooser fileChooser=new JFileChooser();

        int returnVal = fileChooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            String st = file.getAbsolutePath();
            String nama = "File torrent dari "+file.getName()+" berhasil dibuat";   //nama filenya
            String dir = file.getParent();
            
            try {
              // What to do with the file, e.g. display it in a TextArea
                
                //String path = new String();
                
                tor.createTorrent(st);
                tor.saveToFile(dir);

                //peersinfo.read(new StringReader(dir), null);
                generalinfo.read( new StringReader( nama ), null );

                tor = new Torrent(st + ".torrent");
                JOptionPane.showMessageDialog(frame, "File torrent berhasil dibuat : \n"+st+".torrent");


            } catch (IOException ex) {
              System.out.println("problem accessing file"+file.getAbsolutePath());
            }
        } else {
            System.out.println("File access cancelled by user.");
        }
    }//GEN-LAST:event_createtorrentActionPerformed

    private void popupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_popupActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_popupActionPerformed

    private void aboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutActionPerformed
        // TODO add your handling code here:

        JOptionPane.showMessageDialog(frame, "Program ThisTorrent \nCredit : \nListiargo Wastuargo\nEric Cahya Lesmana\nCandra Alim Sutanto");
        
    }//GEN-LAST:event_aboutActionPerformed

    private void generalinfoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_generalinfoMouseClicked
        // TODO add your handling code here:
}//GEN-LAST:event_generalinfoMouseClicked

    private void menupopupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menupopupActionPerformed
        // TODO add your handling code here:

        popup.show(this, WIDTH, WIDTH);
}//GEN-LAST:event_menupopupActionPerformed

    private void torrentlistMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_torrentlistMouseClicked
        // TODO add your handling code here:
        try {
              // What to do with the file, e.g. display it in a TextArea
            int index = torrentlist.getSelectedIndex();
            if(index!=-1){
                String temp = strings.get(index);

                tor = new Torrent(temp);

                String info = new String();
                info="Nama File : "+tor.getFileName()+"\n";
                info=info+"File Length : "+tor.getFileLength()+"\n";
                info=info+"Length : "+tor.getLength()+"\n";
                //info=info+"Announcement"+"\n";

                StringReader myst = new StringReader(info);
                generalinfo.read(myst, null );

                String infopeer = new String();
                if(arrayTampung.get(index).getPlay()){
                        infopeer = "Daftar Peer yang memiliki file : \n\n";
                        infopeer = infopeer+"Jumlah Peer yang memiliki file complete : "+arrayTampung.get(index).getPer().getResult().getComplete()+"\n";
                        infopeer = infopeer+"Jumlah Peer yang memiliki file incomplete : "+arrayTampung.get(index).getPer().getResult().getIncomplete()+"\n";
                        infopeer = infopeer+"Daftar peer : \n";
                        //System.out.println(arrayTampung.get(index).getRes().getPeers().size());
                        for(int y=0;y<arrayTampung.get(index).getPer().getResult().getPeers().size();y++){
                            infopeer = infopeer+arrayTampung.get(index).getPer().getResult().getPeers().get(y).getAddress().toString()+"\n";
                        }

                    //infopeer = infopeer+"Daftar peer : \n" + index;
                    /*for(int y=0;y<track.getPeers(st).size();y++){
                        infopeer = infopeer+track.getPeers(tor.getFileName()).get(y).getAddress();
                    }*/
                } else {
                    
                    infopeer = "Daftar Peer yang memiliki file : "+tor.getFileName()+" \n\n";
                    infopeer = infopeer+"Jumlah Peer yang memiliki file complete : 0"+"\n";
                    infopeer = infopeer+"Jumlah Peer yang memiliki file incomplete : 0"+"\n";
                }

                

                String fil = new String();
                boolean[] status = tor.compareDownloadedFile(tor.getResultPath());
                for(int y=0;y<status.length;y++){
                    fil+="Part ke "+y;
                    if(status[y]){
                        fil+="\tcompleted\n";
                    }else{
                        fil+="\tnot completed\n";
                    }
                }

                myst = new StringReader(fil);
                files.read(myst, null);
                    
                for(int y=0;y<tor.getFileLength()/tor.getLength()+1;y++){
                    JPanel panel1 = new JPanel();
                    Border b = BorderFactory.createLineBorder(Color.black);
                    panel1.setBorder(b);
                    pane.add(panel1);
                    files.add(panel1);
                }

                StringReader myst1 = new StringReader(infopeer);
                peersinfo.read(myst1, null);

            }
            } catch (IOException ex) {
              
            }
        
    }//GEN-LAST:event_torrentlistMouseClicked

    private void deleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteActionPerformed
        // TODO add your handling code here:
        try {
              // What to do with the file, e.g. display it in a TextArea
                int index = torrentlist.getSelectedIndex();
                if(index!=-1){
                    if(!arrayTampung.get(index).getPlay()){
                        strings.remove(index);

                        final String[] daftar = new String[strings.size()];
                            strings.toArray(daftar);

                            torrentlist.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
                            torrentlist.setLayoutOrientation(JList.VERTICAL_WRAP);
                            torrentlist.setVisibleRowCount(-1);
                            torrentlist.setModel(new javax.swing.AbstractListModel() {
                                String[] strings = daftar;
                                public int getSize() { return strings.length; }
                                public Object getElementAt(int i) { return strings[i]; }
                            });


                        String info = new String();
                        info="";

                        //info=info+"Announcement"+"\n";

                        StringReader myst = new StringReader(info);
                        generalinfo.read(myst, null );

                        String infopeer = new String();
                        infopeer = "";

                        /*for(int y=0;y<track.getPeers(st).size();y++){
                            //infopeer = infopeer+track.getPeers(tor.getFileName()).get(y).toString();
                        }*/


                        StringReader myst1 = new StringReader(infopeer);
                        peersinfo.read(myst1, null);
                        files.read(myst, null);

                        arrayTampung.remove(index);
                        torrentGUI.remove(index);
                    }else{
                        JOptionPane.showMessageDialog(frame, "File masih dalam kondisi run\n");
                    }
                }
            } catch (IOException ex) {

            }

    }//GEN-LAST:event_deleteActionPerformed

    private void helpmenuStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_helpmenuStateChanged
        
    }//GEN-LAST:event_helpmenuStateChanged

    private void playActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_playActionPerformed
        int index = torrentlist.getSelectedIndex();
        System.out.println(index+"\n");
        System.out.println(arrayTampung.size()+"\n");

        if(index==-1){
            //do nothing
        }else{
            try {
                //System.out.println(arrayper.get(index).getAddress().toString());
                if(!arrayTampung.get(index).getPlay()){
                    arrayTampung.get(index).setPlay(true);
                    arrayTampung.get(index).getPer().setResult(arrayTampung.get(index).getPer().requestFileToTracker(strings.get(index)));
                    //arrayTampung.get(index).setRes(arrayTampung.get(index).getPer().requestFileToTracker(strings.get(index)));
                    arrayTampung.get(index).getPer().startHandler();

                    // start downloader
                    Tampung selected = arrayTampung.get(index);

                    Torrent selectedTorrent = null;
                    for (int i = 0; i < torrentGUI.size(); ++i) {
                        if (torrentGUI.get(i).getFileName().equals(selected.getPer().getData().getFileName()))
                            selectedTorrent = torrentGUI.get(i);
                    }

                    PeerDownloader downloader = new PeerDownloader(per, selectedTorrent);
                    selected.setDownloader(downloader);
                    downloader.start();

					//System.out.println(selected.getPer());

                    String infopeer = new String();
                    infopeer = "Daftar Peer yang memiliki file : \n\n";
                    infopeer = infopeer+"Jumlah Peer yang memiliki file complete : "+arrayTampung.get(index).getPer().getResult().getComplete()+"\n";
                    infopeer = infopeer+"Jumlah Peer yang memiliki file incomplete : "+arrayTampung.get(index).getPer().getResult().getIncomplete()+"\n";
                    infopeer = infopeer+"Daftar peer : \n";
                    //System.out.println(arrayTampung.get(index).getRes().getPeers().size());
                    for(int y=0;y<arrayTampung.get(index).getPer().getResult().getPeers().size();y++){
                        infopeer = infopeer+arrayTampung.get(index).getPer().getResult().getPeers().get(y).getAddress().toString()+"\n";
                    }
                    
                    StringReader myst1 = new StringReader(infopeer);
                    peersinfo.read(myst1, null);

                    String fil = new String();
                    boolean[] status = tor.compareDownloadedFile(tor.getResultPath());
                    for(int y=0;y<status.length;y++){
                        fil+="Part ke "+y;
                        if(status[y]){
                            fil+="\tcompleted\n";
                        }else{
                            fil+="\tnot completed\n";
                        }
                    }

                    StringReader myst = new StringReader(fil);
                    files.read(myst, null);

                     /*while (isPlay){
                        resp = arrayper.get(index).requestFileToTracker(strings.get(index));
                        for (int j = 0; j < resp.getPeers().size(); ++j){
                            System.out.println(resp.getPeers().get(j).getAddress());
                        }
                        try {
                            Thread.sleep(Utilities.PEER_REQUEST_INTERVAL);
                        } catch (InterruptedException ex){

                        }
                    }*/
                }
                
            } catch (IOException ex) {
                Logger.getLogger(GUITorrent.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        
    }//GEN-LAST:event_playActionPerformed

    private void stopActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stopActionPerformed
        // TODO add your handling code here:
        int index = torrentlist.getSelectedIndex();

        if(index==-1){
            //do nothing
        }else{
            if(arrayTampung.get(index).getPlay()){
                arrayTampung.get(index).getPer().stopHandler();
                arrayTampung.get(index).getDownloader().setRunning(false);

                arrayTampung.get(index).setPlay(false);
                for (int i = 0; i < arrayTampung.get(index).getPer().getResult().getPeers().size(); ++i){
                    System.out.println(arrayTampung.get(index).getPer().getResult().getPeers().get(i).getAddress());
                }
            }
        }


    }//GEN-LAST:event_stopActionPerformed

    public void createFile(long size, String path) throws FileNotFoundException, IOException
    {
        byte[] buf = new byte[8192];
        long n = size;
        FileOutputStream fos = new FileOutputStream(path);
        long m = n / buf.length;
        for (long i = 0; i < m; i++) {
            fos.write(buf, 0, buf.length);
        }
        fos.write(buf, 0, (int)(n % buf.length));
        fos.close();
    }
    
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GUITorrent().setVisible(true);

            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane Files;
    private javax.swing.JButton about;
    private javax.swing.JMenuItem aboutitem;
    private javax.swing.JMenuItem additem;
    private javax.swing.JButton addtorrent;
    private javax.swing.JPanel bodypanel;
    private javax.swing.JMenuItem createitem;
    private javax.swing.JButton createtorrent;
    private javax.swing.JButton delete;
    private javax.swing.JButton down;
    private javax.swing.JMenuItem exititem;
    private javax.swing.JMenu filemenu;
    private javax.swing.JTextField files;
    private javax.swing.JScrollPane general;
    private javax.swing.JTextField generalinfo;
    private javax.swing.JMenu helpmenu;
    private javax.swing.JPanel infopanel;
    private javax.swing.JTabbedPane infotab;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPopupMenu.Separator jSeparator2;
    private javax.swing.JPopupMenu.Separator jSeparator3;
    private java.awt.Menu menupopup;
    private javax.swing.JScrollPane peers;
    private javax.swing.JTextField peersinfo;
    private javax.swing.JButton play;
    private java.awt.PopupMenu popup;
    private javax.swing.JScrollPane scrollinfo;
    private javax.swing.JButton stop;
    private javax.swing.JList torrentlist;
    private javax.swing.JButton up;
    // End of variables declaration//GEN-END:variables
    private ArrayList<String> strings = new ArrayList<String>();
    private static Peer per = new Peer("127.0.0.1");
    private Torrent tor = new Torrent();
    private Response resp = new Response();
    private ArrayList<JPanel> pane = new ArrayList<JPanel>();
    private ArrayList<Tampung> arrayTampung = new ArrayList<Tampung>();
    public static ArrayList<Torrent> torrentGUI = new ArrayList<Torrent>();


    public class Tampung{
        private Peer per;
        private boolean isPlay;
        private PeerDownloader downloader;

        public Tampung (){
            //
        }

        public Tampung(Peer p, boolean b){
            this.per = new Peer();
            this.per = p;
            this.isPlay = b;
        }

        public Peer getPer(){
            return this.per;
        }

        public boolean getPlay(){
            return this.isPlay;
        }


        public PeerDownloader getDownloader() {
            return this.downloader;
        }

        public void setPer(Peer p){
            this.per = p;
        }
        

        public void setPlay(boolean p){
            this.isPlay = p;
        }

        public void setDownloader(PeerDownloader d) {
            if (downloader != null) {
                downloader.setRunning(false);

                try {
                    downloader.join();
                } catch (InterruptedException iEx) {
                    
                }
            }
            downloader = d;
        }
    }
    
    // This class extends Thread
    static class BasicThread extends Thread {
        // This method is called when the thread runs
        @Override
        public void run() {
			try {
				ServerSocket serverSocket = new ServerSocket(Utilities.PEER_PORT);
				if(serverSocket.isBound()){
					System.out.println("Server socket berhasil dibuat\n");
				}
				while(run){

					Socket clientSocket = null;

					try {
						clientSocket = serverSocket.accept();
						PeerHandler ph = new PeerHandler(clientSocket, torrentGUI);
						ph.start();
					} catch (IOException e) {
						System.out.println("Accept failed: "+Utilities.PEER_PORT);
					}

				}
			} catch (IOException e) {
				System.out.println("Could not listen on port: "+Utilities.PEER_PORT + e);
			}
        }
        
        /*public void check(){
                for (int j = 0; j < resp.getPeers().size(); ++j){
                    System.out.println(resp.getPeers().get(j).getAddress());
                }
                try {
                    Thread.sleep(Utilities.PEER_REQUEST_INTERVAL);
                } catch (InterruptedException ex){

                }
        }*/

        private boolean run = true;
    }
}
